<template>
  <div>
    <Search :search="search" :reset="reset" style="padding-bottom: 0">
      <template v-slot:body>
        <el-form-item label="工单 :" prop="fbillno">
          <el-input v-model="query.fbillno" name="fbillno" clearable />
        </el-form-item>
        <el-form-item label="生产订单 :" prop="fmobillno">
          <el-input v-model="query.fmobillno" name="fmobillno" clearable />
        </el-form-item>
        <el-form-item label="领料状态 :" prop="back_status">
          <!-- <el-input v-model="query.back_status" name="back_status" clearable /> -->
          <el-select v-model="query.back_status" placeholder="选择状态">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料编码 :" prop="fmaterialid1">
          <el-input v-model="query.fmaterialid1" name="fmaterialid1" clearable />
        </el-form-item>
        <el-form-item label="物料名称 :" prop="fmaterialname1">
          <el-input v-model="query.fmaterialname1" name="fmaterialname1" clearable />
        </el-form-item>
        <el-form-item label="产品编码 :" prop="fmaterialid">
          <el-input v-model="query.fmaterialid" name="fmaterialid" clearable />
        </el-form-item>
        <el-form-item label="范围日期 :" prop="date">
          <el-config-provider :locale="locale">
            <el-date-picker v-model="query.date" type="daterange" range-separator="至" format="YYYY-MM-DD" value-format="YYYY-MM-DD" start-placeholder="开始时间" end-placeholder="结束时间" />
          </el-config-provider>
        </el-form-item>
        <!-- <el-form-item prop="start_date"></el-form-item>
        <el-form-item prop="end_date"></el-form-item> -->
      </template>
    </Search>

    <div class="table-default">
      <div class="btn-view">
        <el-button type="primary" @click="backHandler">返回</el-button>
        <el-button type="warning" @click="outputHandler">导出</el-button>
        <div class="step-view" v-if="showStep"><el-progress :percentage="percentage" /></div>
      </div>
      <el-table :data="tableData" class="mt-3" v-loading="loading" border>
        <el-table-column label="工单号" prop="order.fbillno" width="150" />
        <el-table-column label="物料编码" prop="fmaterialid1" width="150" />
        <el-table-column label="物料名称" prop="fmaterialname1" width="200" />
        <el-table-column label="领料状态" prop="back_status" width="110">
          <template #default="scope">
            <el-tag class="ml-2" type="success" v-if="scope.row.back_status == 2">{{ statusformatter[scope.row.back_status] }}</el-tag>
            <el-tag class="ml-2" type="warning" v-if="scope.row.back_status == 1">{{ statusformatter[scope.row.back_status] }}</el-tag>
            <el-tag class="ml-2" type="primary" v-if="scope.row.back_status == 0">{{ statusformatter[scope.row.back_status] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分子" prop="fnumerator" width="80">
          <template #default="scope">
            {{ Number(scope.row.fnumerator) }}
          </template>
        </el-table-column>
        <el-table-column label="分母" prop="fdenominator" width="80">
          <template #default="scope">
            {{ Number(scope.row.fdenominator) }}
          </template>
        </el-table-column>
        <el-table-column label="物料单位" prop="funitid1_name" width="100" />
        <el-table-column label="应发数量" prop="fmustqty" width="100">
          <template #default="scope">
            {{ Number(scope.row.fmustqty) }}
          </template>
        </el-table-column>
        <el-table-column label="已领数量" prop="fpickedqty" width="100">
          <template #default="scope">
            {{ Number(scope.row.fpickedqty) }}
          </template>
        </el-table-column>
        <el-table-column label="工艺流程" prop="order.flow_name" width="100" />
        <el-table-column label="产品编码" prop="order.fmaterialid" width="100" />
        <el-table-column label="产品名称" prop="order.fmaterialname" width="150" />
        <el-table-column label="产品规格" prop="order.fmaterialmodel" width="100" />
        <el-table-column label="产品型号" prop="order.fmodel" width="100" />
        <el-table-column label="产品单位" prop="order.funitid_name" width="100" />
        <el-table-column label="创建开始时间" prop="created_at" width="150" />
      </el-table>
      <Paginate />
    </div>

    <Dialog v-model="visible" :title="title" destroy-on-close>
      <Create @close="close(reset)" :primary="id" :api="api" />
    </Dialog>
  </div>
</template>
  
  <script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useGetList } from '/admin/composables/curd/useGetList'
import { useDestroy } from '/admin/composables/curd/useDestroy'
import { useOpen } from '/admin/composables/curd/useOpen'
import http from '/admin/support/http'
import zhCn from 'element-plus/lib/locale/lang/zh-cn'
import { setTableHeight } from '/admin/utils/setHeight.js'
import { delDetailRouter } from '/admin/utils/delDetailRouter'

import { useRouter, useRoute } from 'vue-router'
let router = useRouter()
let route = useRoute()
const locale = ref(zhCn)
const api = `production/back/report`

const { data, query, search, reset, loading } = useGetList(api, 10)
const { destroy, deleted } = useDestroy()
const { open, close, title, visible, id } = useOpen()

const tableData = computed(() => data.value?.data)

if (route.query.back_status) query.value.back_status = Number(route.query.back_status)

const statusList = ref([
  {
    label: '已领料',
    value: 1,
  },
  {
    label: '未领料完',
    value: 0,
  },
  {
    label: '全部',
    value: '',
  },
])
let statusformatter = reactive({})

watch(query.value, (newVal, oldVal) => {
  if (newVal.date) {
    // console.log('获取范围时间', query.value.date)
    query.value.start_date = query.value.date[0]
    query.value.end_date = query.value.date[1]
    // console.log(query.value);
  }
})

//  状态枚举
const getStatus = () => {
  http.get('/options/ProductionOrderBackStatus').then(r => {
    console.log('领料状态数据', r.data.data)
    if (r.data.code == 10000) {
      // statusList.value = r.data.data
      statusformatter = r.data.data.reduce((acc, item) => {
        acc[item.value] = item.label
        return acc
      }, {})
      console.log('转换状态', statusformatter)
    } else {
      ElMessage.error(r.data.message)
    }
  })
}
getStatus()

// // 导出
// const outputHandler = () => {
//   console.log(query.value)
//   let sendData = {
//     limit: query.value.limit,
//     page: query.value.page,
//     obj_id: null,
//   }
//   http.get('/excel/export/BackDetail', sendData).then(r => {
//     if (r.data.code == 10000) {
//       console.log('导出备货计划看板', r.data.data)
//       // 返回数据，当finish ！= 1 ，继续请求，第二次请求需要带上返回的obj_id，和limit，page，每次请求page自增1，当page==total_page，且返回finish ==1 ，停止请求
//     //   "data": {
//     //     "job_id": "1696754727",
//     //     "total": 40,
//     //     "limit": 10,
//     //     "total_page": 4,
//     //     "page": 1,
//     //     "finish": 0,
//     //     "excel_url": ""
//     // }
//     } else {
//       ElMessage.error(r.data.message)
//     }
//   })
// }

// let total_page = ref(0)
// let curpage = ref(0)
let percentage = ref(0)
let showStep = ref(false)
// 导出
const outputHandler = async () => {
  showStep.value = true
  try {
    console.log(query.value)
    let sendData = {
      ...query.value,
      limit: 1000,
      job_id: null,
    }
    await sendRequest(sendData)
  } catch (error) {
    console.error(error)
  }
}

const sendRequest = async sendData => {
  try {
    const response = await http.get('/excel/export/BackDetail', sendData)
    if (response.data.code == 10000) {
      console.log('导出备货计划看板', response.data.data)
      let data = response.data.data
      if (data.finish != 1) {
        sendData.job_id = data.job_id
        sendData.page++
        percentage.value = parseInt((sendData.page * 100) / data.total_page)
        await sendRequest(sendData)
      } else {
        console.log('打印完成，拿到下载表格', data.excel_url)
        // downloadFile(data.excel_url)
        // const w = window.open('about:blank')
        // w.location.href = data.excel_url
        window.location.href = data.excel_url
        setTimeout(() => {
          showStep.value = false
        }, 1000*60)
      }
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    console.error(error)
  }
}

// const stepformat = (percentage) => (percentage == total_page.value ? '完成' : `${curpage.value / total_page.value }%`)

// 返回
const backHandler = () => {
  delDetailRouter('备货计划详情', '/production/StockBoard')
}


onMounted(() => {
  search()
  deleted(reset)
  setTableHeight('.table-default')
})
</script>

<style lang="css" scoped>
.el-table {
  height: 80%;
}
.btn-view {
  display: flex;
}
.step-view {
  margin-left: 10px;
  width: 20vw;
  /* border: 1px solid #000; */
  padding-top: 0.5rem;
  box-sizing: border-box;
}
</style>
  